{% extends "members/base.html" %}

{% block title %}量表库{% endblock %}

{% block extra_css %}
<style>
    .library-header {
        background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
        color: white;
        padding: 2rem;
        border-radius: 10px;
        margin-bottom: 2rem;
    }
    .search-section {
        background: white;
        border: 1px solid #e9ecef;
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .category-filter {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 1rem;
    }
    .category-btn {
        padding: 0.5rem 1rem;
        border: 1px solid #dee2e6;
        border-radius: 20px;
        background: white;
        color: #6c757d;
        text-decoration: none;
        transition: all 0.2s;
        font-size: 0.9rem;
    }
    .category-btn:hover, .category-btn.active {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }
    .scale-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 1.5rem;
    }
    .scale-card {
        border: 1px solid #e9ecef;
        border-radius: 10px;
        padding: 1.5rem;
        background: white;
        transition: all 0.3s;
        height: 100%;
        display: flex;
        flex-direction: column;
    }
    .scale-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        border-color: #007bff;
    }
    .scale-meta {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
        font-size: 0.85rem;
        color: #6c757d;
    }
    .scale-stats {
        display: flex;
        justify-content: space-between;
        margin: 1rem 0;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;
    }
    .stat-item {
        text-align: center;
        flex: 1;
    }
    .stat-value {
        font-weight: bold;
        color: #007bff;
        font-size: 1.2rem;
    }
    .stat-label {
        font-size: 0.8rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }
    .price-badge {
        position: absolute;
        top: 1rem;
        right: 1rem;
        padding: 0.25rem 0.5rem;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    .price-free {
        background: #d4edda;
        color: #155724;
    }
    .price-paid {
        background: #fff3cd;
        color: #856404;
    }
    .card-actions {
        margin-top: auto;
        padding-top: 1rem;
    }
    .sort-controls {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
    }
    .result-info {
        display: flex;
        justify-content: between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        color: #6c757d;
    }
    .empty-state i {
        font-size: 4rem;
        opacity: 0.5;
        margin-bottom: 1rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="library-header">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h2 class="mb-2">量表库</h2>
                <p class="mb-0">发现和使用专业的心理测评量表</p>
            </div>
            <div class="col-md-4 text-end">
                <div class="d-flex align-items-center justify-content-end text-white">
                    <i class="bi bi-collection me-2"></i>
                    <span>总共 <strong id="total-count">-</strong> 个量表</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
        <div class="row">
            <div class="col-md-8">
                <div class="input-group">
                    <input type="text" class="form-control" id="search-input" placeholder="搜索量表标题或描述...">
                    <button class="btn btn-primary" type="button" onclick="searchScales()">
                        <i class="bi bi-search me-1"></i>搜索
                    </button>
                </div>
            </div>
            <div class="col-md-4">
                <select class="form-select" id="sort-select" onchange="sortScales()">
                    <option value="newest">最新发布</option>
                    <option value="popular">最受欢迎</option>
                    <option value="name">按名称</option>
                    <option value="category">按分类</option>
                </select>
            </div>
        </div>
        
        <!-- 分类筛选 -->
        <div class="category-filter" id="category-filter">
            <a href="#" class="category-btn active" data-category="" onclick="filterByCategory('')">全部</a>
        </div>
    </div>

    <!-- 结果信息和控制 -->
    <div class="result-info">
        <div class="d-flex align-items-center">
            <span class="text-muted" id="result-text">正在加载量表...</span>
        </div>
        <div class="d-flex align-items-center gap-3">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="free-only" onchange="filterScales()">
                <label class="form-check-label" for="free-only">仅显示免费</label>
            </div>
        </div>
    </div>

    <!-- 量表列表 -->
    <div id="scales-container">
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载量表...</p>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container" class="mt-4"></div>
</div>

<!-- 量表详情模态框 -->
<div class="modal fade" id="scaleDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modal-scale-title">量表详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="modal-scale-content">
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="mt-2">正在加载详情...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="start-assessment-btn">开始测评</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentPage = 1;
let currentCategory = '';
let currentSearch = '';
let currentSort = 'newest';
let currentFreeOnly = false;
let categories = [];
let scales = [];

// 页面加载
document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    loadScales();
    
    // 搜索框回车事件
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchScales();
        }
    });
});

// 加载分类
function loadCategories() {
    apiRequest('/api/scales/categories')
        .then(response => {
            if (response.success) {
                categories = response.data.categories;
                renderCategoryFilter();
            }
        })
        .catch(error => {
            console.error('加载分类失败:', error);
        });
}

// 渲染分类筛选
function renderCategoryFilter() {
    const container = document.getElementById('category-filter');
    let html = '<a href="#" class="category-btn active" data-category="" onclick="filterByCategory(\'\')">全部</a>';
    
    categories.forEach(category => {
        html += `<a href="#" class="category-btn" data-category="${category.id}" onclick="filterByCategory('${category.id}')">${category.name}</a>`;
    });
    
    container.innerHTML = html;
}

// 加载量表
function loadScales(page = 1) {
    currentPage = page;
    
    let url = `/api/scales?page=${page}&per_page=12`;
    
    if (currentCategory) {
        url += `&category_id=${currentCategory}`;
    }
    if (currentSearch) {
        url += `&search=${encodeURIComponent(currentSearch)}`;
    }
    if (currentFreeOnly) {
        url += `&is_free=true`;
    }
    
    // 排序参数
    switch (currentSort) {
        case 'popular':
            // API默认按使用次数排序
            break;
        case 'name':
            url += `&sort=title`;
            break;
        case 'category':
            url += `&sort=category`;
            break;
        default: // newest
            url += `&sort=created_at`;
            break;
    }
    
    apiRequest(url)
        .then(response => {
            if (response.success) {
                scales = response.data.scales;
                renderScales(scales);
                renderPagination(response.data.pagination);
                updateResultInfo(response.data.pagination.total);
            } else {
                showError('加载量表失败: ' + response.message);
            }
        })
        .catch(error => {
            console.error('加载量表失败:', error);
            showError('加载量表失败，请稍后重试');
        });
}

// 渲染量表列表
function renderScales(scales) {
    const container = document.getElementById('scales-container');
    
    if (!scales || scales.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-search"></i>
                <h4>没有找到量表</h4>
                <p>尝试调整搜索条件或浏览其他分类</p>
            </div>
        `;
        return;
    }
    
    let html = '<div class="scale-grid">';
    
    scales.forEach(scale => {
        html += `
            <div class="scale-card position-relative">
                <div class="price-badge ${scale.is_free ? 'price-free' : 'price-paid'}">
                    ${scale.is_free ? '免费' : '¥' + scale.price}
                </div>
                
                <div class="scale-meta">
                    <span><i class="bi bi-tag me-1"></i>${scale.category_name || '未分类'}</span>
                    <span><i class="bi bi-person me-1"></i>${scale.publisher_name || '系统'}</span>
                    <span><i class="bi bi-eye me-1"></i>${scale.usage_count || 0}次使用</span>
                </div>
                
                <h5 class="mb-2">${escapeHtml(scale.title)}</h5>
                ${scale.subtitle ? `<p class="text-muted small mb-2">${escapeHtml(scale.subtitle)}</p>` : ''}
                <p class="text-muted mb-3">${escapeHtml(scale.description)}</p>
                
                <div class="scale-stats">
                    <div class="stat-item">
                        <div class="stat-value">${scale.question_count || 0}</div>
                        <div class="stat-label">题目数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${scale.estimated_time || '-'}</div>
                        <div class="stat-label">预估时间(分钟)</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${scale.version || '1.0'}</div>
                        <div class="stat-label">版本</div>
                    </div>
                </div>
                
                <div class="card-actions">
                    <div class="d-flex gap-1 mb-2">
                        <button type="button" class="btn btn-outline-primary flex-fill" onclick="viewScaleDetail(${scale.id})">
                            <i class="bi bi-info-circle me-1"></i>详情
                        </button>
                        ${scale.can_copy ? `
                            <button type="button" class="btn btn-outline-success" onclick="copyScale(${scale.id}, '${escapeHtml(scale.title)}')" title="复制到我的量表">
                                <i class="bi bi-copy"></i>
                            </button>
                        ` : ''}
                    </div>
                    <button type="button" class="btn btn-primary w-100" onclick="startAssessment(${scale.id})" ${scale.can_use ? '' : 'disabled'}>
                        <i class="bi bi-play-circle me-1"></i>${scale.can_use ? '开始测评' : '需要更高会员级别'}
                    </button>
                    ${!scale.can_use && scale.min_member_level ? `
                        <small class="text-muted mt-1 d-block text-center">需要 ${getLevelText(scale.min_member_level)} 及以上</small>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    container.innerHTML = html;
}

// 渲染分页
function renderPagination(pagination) {
    const container = document.getElementById('pagination-container');
    
    if (pagination.pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let html = '<nav><ul class="pagination justify-content-center">';
    
    // 上一页
    if (pagination.has_prev) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadScales(${pagination.page - 1})">上一页</a></li>`;
    }
    
    // 页码
    const startPage = Math.max(1, pagination.page - 2);
    const endPage = Math.min(pagination.pages, pagination.page + 2);
    
    if (startPage > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadScales(1)">1</a></li>`;
        if (startPage > 2) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === pagination.page ? 'active' : '';
        html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="loadScales(${i})">${i}</a></li>`;
    }
    
    if (endPage < pagination.pages) {
        if (endPage < pagination.pages - 1) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadScales(${pagination.pages})">${pagination.pages}</a></li>`;
    }
    
    // 下一页
    if (pagination.has_next) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadScales(${pagination.page + 1})">下一页</a></li>`;
    }
    
    html += '</ul></nav>';
    container.innerHTML = html;
}

// 更新结果信息
function updateResultInfo(total) {
    document.getElementById('total-count').textContent = total || 0;
    
    let resultText = `找到 ${total || 0} 个量表`;
    if (currentSearch) {
        resultText += ` (搜索: "${currentSearch}")`;
    }
    if (currentCategory) {
        const category = categories.find(c => c.id == currentCategory);
        if (category) {
            resultText += ` (分类: ${category.name})`;
        }
    }
    if (currentFreeOnly) {
        resultText += ` (仅免费)`;
    }
    
    document.getElementById('result-text').textContent = resultText;
}

// 搜索功能
function searchScales() {
    currentSearch = document.getElementById('search-input').value.trim();
    currentPage = 1;
    loadScales();
}

// 分类筛选
function filterByCategory(categoryId) {
    currentCategory = categoryId;
    currentPage = 1;
    
    // 更新按钮状态
    document.querySelectorAll('.category-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    loadScales();
}

// 排序
function sortScales() {
    currentSort = document.getElementById('sort-select').value;
    currentPage = 1;
    loadScales();
}

// 筛选
function filterScales() {
    currentFreeOnly = document.getElementById('free-only').checked;
    currentPage = 1;
    loadScales();
}

// 查看量表详情
function viewScaleDetail(scaleId) {
    document.getElementById('modal-scale-content').innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2">正在加载详情...</p>
        </div>
    `;
    
    const modal = new bootstrap.Modal(document.getElementById('scaleDetailModal'));
    modal.show();
    
    apiRequest(`/api/scales/${scaleId}`)
        .then(response => {
            if (response.success) {
                renderScaleDetail(response.data);
                document.getElementById('start-assessment-btn').onclick = () => {
                    modal.hide();
                    startAssessment(scaleId);
                };
            } else {
                document.getElementById('modal-scale-content').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle me-2"></i>加载失败: ${response.message}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('加载量表详情失败:', error);
            document.getElementById('modal-scale-content').innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>加载失败，请稍后重试
                </div>
            `;
        });
}

// 渲染量表详情
function renderScaleDetail(scale) {
    document.getElementById('modal-scale-title').textContent = scale.title;
    
    let html = `
        <div class="mb-4">
            ${scale.subtitle ? `<p class="text-muted">${escapeHtml(scale.subtitle)}</p>` : ''}
            <p>${escapeHtml(scale.description)}</p>
            ${scale.instruction ? `<div class="alert alert-info"><strong>测试说明：</strong><br>${escapeHtml(scale.instruction)}</div>` : ''}
        </div>
        
        <div class="row mb-4">
            <div class="col-md-6">
                <h6>基本信息</h6>
                <ul class="list-unstyled">
                    <li><strong>分类：</strong>${scale.category_name || '未分类'}</li>
                    <li><strong>发布者：</strong>${scale.publisher_name || '系统'}</li>
                    <li><strong>作者：</strong>${scale.author || '-'}</li>
                    <li><strong>版本：</strong>${scale.version || '1.0'}</li>
                    <li><strong>题目数：</strong>${scale.question_count || 0} 题</li>
                    <li><strong>预估时间：</strong>${scale.estimated_time || '-'} 分钟</li>
                    <li><strong>使用次数：</strong>${scale.usage_count || 0} 次</li>
                    <li><strong>价格：</strong>${scale.is_free ? '免费' : '¥' + scale.price}</li>
                </ul>
            </div>
            <div class="col-md-6">
                ${scale.copyright_info ? `
                    <h6>版权信息</h6>
                    <p class="small text-muted">${escapeHtml(scale.copyright_info)}</p>
                ` : ''}
            </div>
        </div>
    `;
    
    if (scale.questions && scale.questions.length > 0) {
        html += `
            <h6>题目预览</h6>
            <div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
        `;
        
        scale.questions.slice(0, 3).forEach((question, index) => {
            html += `
                <div class="mb-3">
                    <p><strong>${index + 1}. ${escapeHtml(question.question_text)}</strong></p>
            `;
            
            if (question.options && question.options.length > 0) {
                question.options.forEach(option => {
                    html += `
                        <div class="form-check">
                            <input class="form-check-input" type="${question.question_type === 'multiple' ? 'checkbox' : 'radio'}" disabled>
                            <label class="form-check-label">${escapeHtml(option.option_text)}</label>
                        </div>
                    `;
                });
            }
            
            html += '</div>';
        });
        
        if (scale.questions.length > 3) {
            html += `<p class="text-muted small">... 还有 ${scale.questions.length - 3} 个题目</p>`;
        }
        
        html += '</div>';
    }
    
    document.getElementById('modal-scale-content').innerHTML = html;
}

// 复制量表
function copyScale(scaleId, scaleTitle) {
    if (!confirm(`确定要复制量表"${scaleTitle}"到您的量表库吗？`)) {
        return;
    }
    
    // 显示加载状态
    const button = event.target.closest('button');
    const originalContent = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<i class="spinner-border spinner-border-sm me-1"></i>复制中...';
    
    apiRequest(`/api/scales/copy/${scaleId}`, {
        method: 'POST',
        body: JSON.stringify({
            title: `${scaleTitle} (副本)`
        })
    })
    .then(response => {
        if (response.success) {
            alert('量表复制成功！您可以在"我的量表"中查看和编辑。');
        } else {
            alert('复制失败: ' + response.message);
        }
    })
    .catch(error => {
        console.error('复制量表失败:', error);
        alert('复制失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        button.disabled = false;
        button.innerHTML = originalContent;
    });
}

// 获取会员级别文本
function getLevelText(level) {
    const texts = {
        'basic': '基础会员',
        'professional': '专业会员', 
        'institution': '机构会员',
        'research': '科研会员'
    };
    return texts[level] || level;
}

// API请求函数已在base.html中定义，无需重复定义

// 开始测评
function startAssessment(scaleId) {
    apiRequest(`/api/scales/${scaleId}/start`, {
        method: 'POST'
    })
    .then(response => {
        if (response.success) {
            const assessmentId = response.data.id;
            // 跳转到测评页面
            window.location.href = `/assessment/${assessmentId}`;
        } else {
            alert('开始测评失败: ' + response.message);
        }
    })
    .catch(error => {
        console.error('开始测评失败:', error);
        alert('开始测评失败，请稍后重试');
    });
}

// 工具函数
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showError(message) {
    const container = document.getElementById('scales-container');
    container.innerHTML = `
        <div class="alert alert-danger" role="alert">
            <i class="bi bi-exclamation-triangle me-2"></i>${message}
        </div>
    `;
}
</script>
{% endblock %}